import os
from datetime import datetime

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import View

from demo.forms import ArticleForm
from demo.models import *
from dj_study.settings import MEDIA_ROOT


def test(request, **kwargs):
    user = User.objects.get(username='zhangs')
    print(user.check_password('qwe124'))
    # info = kwargs.get("info")
    # print(info, type(info))
    # print('test')
    # 一对一表数据添加
    # 创建的用户对象
    # user = User(username='test1')
    # user.set_password('qwe123')
    # user.save()
    # # 关联用户表里面的数据 直接关联创建的用户对象
    # UserDetail.objects.create(age=18, sex=1, user=user)

    # 一对一表数据查询
    # 得到用户名为test1的用户详情信息，年龄字段值
    # user = User.objects.get(username='test1')
    # # 用户表关联了用户详情表 用户详情表会成为用户对象的属性
    # # 模型对象会具备 关联表名小写 的属性
    # print(user.userdetail.age)
    #
    # #查询用户详情表id为1的用户名
    # userdetail=UserDetail.objects.get(id=1)
    # print(userdetail.user.username)

    # 一对多表数据添加
    # classes = Classes.objects.create(name='python')
    #
    # article = Article(title="python测试2", desc='python测试2简介', content='python测试2文章内容',
    #                   cover='/media/flower.jpg',
    #                   user_id=1, classes_id=1
    #                   )
    # article.save()
    # 一对多表数据查询
    # 管理器
    # classes=Classes.objects.get(name='python')
    # 得到的多条数据 filter
    # print(classes.article_set.all())

    # article=Article.objects.get(title='python测试一')
    # #得到是一条数据 get
    # print(article.classes.name)
    # article=Article.objects.get(title='python测试2')
    # article.classes_id=2
    # article.save()

    # 得到test分类对象
    classes = Classes.objects.get(name='python')
    classes.article_set.add(Article.objects.get(title='python测试2'))

    # 多对多数据添加
    # article = Article.objects.get(title='python测试2')

    # article.label.create(name='测试一')
    # article.label.create(name="测试二")

    # 多对多表数据删除 关系表数据
    # res = Label.objects.get(name="测试一")
    # print(res)
    # 清空
    # article.label.clear()
    # article.label.remove(res)
    # Label.objects.get(name="测试二").delete()
    # 多对多的表数据查询
    # userdetail = UserDetail.objects.get(id=1)
    # Classes.objects.get(article__user__userdetail=1)
    # res=UserDetail.objects.get(user__article__classes=1)
    # print(res)

    return HttpResponse("成功")


def re_test(request, **kwargs):
    return HttpResponse("这是re_path规则接受的参数")


# Y:四位数的年  y：两位的年
# m：两位数的月 n：一位的月
# d：两位数的日 j：一位的日
# g 12小时制的一位数的小时
# G 24小时制的一位数的小时
# h 12小时制的两位数的小时
# H 24小时制的两位位数的小时
# i 分钟 s秒钟


user = None


# 模型
def nav(request, **kwargs):
    # 通过不定长获取到地址中的分类名是python还是java
    username = request.session.get("username")
    classes = kwargs.get('classes')
    res = Classes.objects.get(name=classes)
    print(res.article_set.all())
    if not res:
        return redirect("not_found")

    # if classes not in list(data.keys()):
    #     print(reverse("not_found"))
    #     return redirect("not_found")
    # 通过python键获取到文字数据

    # 是我的网站没有这个分类
    # if not res:
    #     return redirect("not_found")
    # return HttpResponse(article)
    return HttpResponse(render(request, 'demo/nav.html', context={'articles': res.article_set.all(),
                                                                  "html": "<h1>hello django</h1>",
                                                                  "classes": Classes.objects.all(),
                                                                  "now_classes": classes,
                                                                  "username": username,
                                                                  }))


def not_found(request, **kwargs):
    return HttpResponse("小主走错路了~")


def index(request, **kwargs):
    # 获取请求种的cookie，然后到数据种的session匹配
    username = request.session.get("username")
    return HttpResponse(render(request, 'demo/index.html', context={
        "classes": Classes.objects.all(),
        # "str1":'hello world hello xiaomeng'
        "username": username,
    }))


def update_classes(request, **kwargs):
    # 修改单条数据
    # res = Classes.objects.get(name="python")
    # res.name = "python3"
    # res.save()
    # 修改多条数据
    Classes.objects.filter(name="java").update(name="javaee")
    return HttpResponse("修改数据成功")


def delete_classes(request, **kwargs):
    # Classes.objects.get(name="mcp").delete()
    Classes.objects.filter(name="javaee").delete()
    return HttpResponse("删除数据成功")


def find_func(request, **kwargs):
    res = Classes.objects.first()
    res = Classes.objects.last()
    # 排除查询
    res = Classes.objects.exclude(name="python3")
    # 排序 方向排序只需要在字段前面加负号
    res = Classes.objects.order_by('-id')
    print(res)
    return HttpResponse(f"{res}查询成功")


def find_conditions(request, **kwargs):
    print("忽略大小写", Classes.objects.filter(name__iexact="DEEPSEEK"))
    print("包含", Classes.objects.filter(name__icontains='D'))
    print('以什么开头', Classes.objects.filter(name__istartswith="D"))
    print('以什么结尾', Classes.objects.filter(name__iendswith="P"))
    print("成员", Classes.objects.filter(name__in=["python3", "jave"]))
    print("大于", Classes.objects.filter(id__gt=2))
    print("大于等于", Classes.objects.filter(id__gte=2))
    print("小于等于", Classes.objects.filter(id__lte=2))
    print("小于", Classes.objects.filter(id__lt=2))
    print("区间", Classes.objects.filter(id__range=(2, 5)))
    print("判断是否为空", Classes.objects.filter(name__isnull=False))
    return HttpResponse("查询成功")


class AddArticleView(View):
    # 装饰器的功能检查是否已经登录了用户，如果没有就跳转到登录页
    @method_decorator(login_required)
    def get(self, request):
        form = ArticleForm()
        # username=request.session.get('username')
        username = request.user.username
        return render(request, 'demo/add_article.html', {"username": username, "form": form})

    def post(self, request, *args, **kwargs):
        form = ArticleForm(request.POST, request.FILES)
        print(request.POST)
        print(request.FILES)
        username = request.user.username
        if form.is_valid():
            print("通过校验")
            title = form.cleaned_data.get("title")
            desc = form.cleaned_data.get("desc")
            content = form.cleaned_data.get("content")
            cover = form.cleaned_data.get("cover")
            # 获取用户对象
            user = request.user
            classes = form.cleaned_data.get("classes")
            # 多对多 得到的queryset
            label = form.cleaned_data.get("label")
            # 时间戳+用户上传的文件名
            file_name = f'{datetime.now().strftime("%Y%m%d%H%M%S")}_{cover.name}'
            with open(os.path.join(MEDIA_ROOT, file_name), 'wb') as fp:
                # 图片比较大 chunks把图片数据划分批次
                for data in cover.chunks():
                    fp.write(data)

            article = Article.objects.create(title=title, desc=desc, content=content, cover=file_name, user=user,
                                             classes=classes)
            for i in label:
                article.label.add(i)

        else:
            print("没有通过校验")
        return render(request, 'demo/add_article.html', {"username": username, "form": form})


class ArticleDetail(View):
    # id 查看一篇文章的内容，通过文章id得到
    def get(self, request, id):
        # 通过地址栏的id得到对应的文章数据
        try:
            # Article.objects.get(id=id) 查询数据库里面是否有这个文章id
            article = Article.objects.get(id=id)
        except Article.DoesNotExist:
            return redirect("not_found")
        return render(request, 'demo/article_detail.html', {"article": article,
                                                            'username': request.user.username,
                                                            'labels': article.label.all()
                                                            })


class ArticleUser(View):
    @method_decorator(login_required)
    def get(self, request):
        articles = Article.objects.filter(user=request.user)
        # 数据库里面的数据 一个页面显示几条数据
        pg = Paginator(articles, 2)
        try:
            pg_current = request.GET.get('page')  # 获取到当前的页码
            # 获取当前页面的数据
            pages = pg.page(pg_current)
        except PageNotAnInteger:
            # 如果页面值不是整数，默认显示第一页
            pages = pg.page(1)
        except EmptyPage:
            # 如果页面值有效，但是没有数据，默认显示最后一页
            pages = pg.page(pg.num_pages)
        return render(request, 'demo/user_article.html', {"username": request.user.username,
                                                          # "articles": articles,
                                                          "pages": pages,
                                                          })


class ArticleUpdate(View):
    @method_decorator(login_required)
    def get(self, request, id):

        try:
            # Article.objects.get(id=id) 查询数据库里面是否有这个文章id
            article = Article.objects.get(id=id)
        except Article.DoesNotExist:
            return redirect("not_found")
        else:
            # 保存修改之前的文章数据
            data = {
                'title': article.title,
                "desc": article.desc,
                "content": article.content,
                "classes": article.classes,
                "label": article.label.all()
            }
            form = ArticleForm(data)
        return render(request, 'demo/update_article.html', {"username": request.user.username, "form": form})

    def post(self, request, id):
        form = ArticleForm(request.POST, request.FILES)
        print(request.POST)
        print(request.FILES)
        username = request.user.username
        if form.is_valid():
            print("通过校验")
            title = form.cleaned_data.get("title")
            desc = form.cleaned_data.get("desc")
            content = form.cleaned_data.get("content")
            cover = form.cleaned_data.get("cover")
            # 获取用户对象
            user = request.user
            classes = form.cleaned_data.get("classes")
            # 多对多 得到的queryset
            label = form.cleaned_data.get("label")
            # 时间戳+用户上传的文件名
            file_name = f'{datetime.now().strftime("%Y%m%d%H%M%S")}_{cover.name}'
            with open(os.path.join(MEDIA_ROOT, file_name), 'wb') as fp:
                # 图片比较大 chunks把图片数据划分批次
                for data in cover.chunks():
                    fp.write(data)
            # 查询获取之前的文章信息
            article = Article.objects.filter(id=id)
            # 删除本地的文件 之前保存的图片
            os.remove(os.path.join(MEDIA_ROOT, article[0].cover))
            article.update(title=title, desc=desc, content=content, cover=file_name, classes=classes)
            article[0].label.clear()
            for i in label:
                article[0].label.add(i)
            return redirect('ArticleUser')

        else:
            print("没有通过校验")
        return render(request, 'demo/add_article.html', {"username": username, "form": form})


class ArticleDelete(View):
    def get(self, request, id):
        try:
            # Article.objects.get(id=id) 查询数据库里面是否有这个文章id
            article = Article.objects.get(id=id)
        except Article.DoesNotExist:
            return redirect("not_found")
        os.remove(os.path.join(MEDIA_ROOT, article.cover))
        article.delete()
        return redirect("ArticleUser")
